package com.ts.proj.json;

import com.ts.base.controller.BaseController;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.SystemConstantEntity;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.service.SystemConstantService;
import com.ts.util.JsonUtils;
import com.ts.util.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class SystemConstantJson extends BaseController {

    @Autowired
    private SystemConstantService systemConstantService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/constant-list/{page}/{size}")
    public Map<String,Object> localConstantList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
        //用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }
        pageData.put("belongTo", user.getBelongTo());
        long count = systemConstantService.count(pageData);
        List<SystemConstantEntity> systemConstantEntities = systemConstantService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", systemConstantEntities);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/constant-ins-upd-del/{id}")
    public Object logCreateUpdate(@PathVariable("id") String id){
        PageData pageData = this.getPageData();
        SystemConstantEntity systemConstantEntity = systemConstantService.findById(Integer.valueOf(id));
        //字段信息维护
        if(null!=pageData.get("constantKey")&&!"".equals(pageData.get("constantKey").toString())){
            systemConstantEntity.setConstantKey(pageData.get("constantKey").toString());
            try{
                if(stringRedisTemplate.hasKey(pageData.getString("constantKey"))){
                    stringRedisTemplate.delete(pageData.getString("constantKey"));
                }
            }catch (Exception e){
            }
        }
        //字段信息维护
        if(null!=pageData.get("constantKeyDesc")&&!"".equals(pageData.get("constantKeyDesc").toString())){
            systemConstantEntity.setConstantKeyDesc(pageData.get("constantKeyDesc").toString());
        }
        //字段信息维护
        if(null!=pageData.get("constantValue")&&!"".equals(pageData.get("constantValue").toString())){
            systemConstantEntity.setConstantValue(pageData.get("constantValue").toString());
        }
        //字段信息维护
        if(null!=pageData.get("constantValueDesc")&&!"".equals(pageData.get("constantValueDesc").toString())){
            systemConstantEntity.setConstantValueDesc(pageData.get("constantValueDesc").toString());
        }
        //
        if(null!=pageData.get("deleteFlag")&&"Y".equals(pageData.get("deleteFlag").toString())){
            systemConstantEntity.setDeleteFlag(pageData.get("deleteFlag").toString());
        }

        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
        systemConstantEntity.setBelongTo(user.getBelongTo());
        systemConstantEntity.setUserId(user.getId());
        systemConstantEntity.setPowerLevel(user.getPowerLevel());

        systemConstantService.save(systemConstantEntity);
        return null;
    }


    /**
     * 通过常量类型，来获取常量列表
     * @param type
     * @return
     */
    @RequestMapping(value = "/constants/{type}")
    public Object constantsByType(@PathVariable("type") String type){
        //先查redis，如果缓存有，直接返回，如果没有查询数据库，在将查询出来的结果存储到缓存中
        List<PageData> pageList = new ArrayList<>();
        PageData pageData = new PageData();
        pageData.put("constantKey", type);
        pageData.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<SystemConstantEntity> all = systemConstantService.findAll(pageData);
        for(SystemConstantEntity systemConstantEntity : all){
            PageData pd = new PageData();
            pd.put("value", systemConstantEntity.getConstantValueDesc());
            pd.put("key", systemConstantEntity.getConstantValue());
            pageList.add(pd);
        }
        return pageList;
    }
    /**
     * 通过常量格式化
     * @param type
     * @return
     */
    @RequestMapping(value = "/constants/{type}/{key}")
    public String constantsByTypeAndKey(@PathVariable("type") String type,@PathVariable("key") String key){
        String result = "";
        PageData pageData = new PageData();
        pageData.put("constantKey", type);
        pageData.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<SystemConstantEntity> all = systemConstantService.findAll(pageData);
        for(SystemConstantEntity systemConstantEntity : all){
            if(systemConstantEntity.getConstantValue().equals(key)){
                result = systemConstantEntity.getConstantValueDesc();
                break;
            }
        }
        return result;
    }
}
